package utils

import (
	"tdy-backend/global"

	"github.com/dgrijalva/jwt-go"
)

type CustomClaims struct {
	Relation string `json:"relation"`
	jwt.StandardClaims
}

func GenerateToken(relation string, expire int64) (string, error) {
	claims := CustomClaims{
		relation,
		jwt.StandardClaims{
			ExpiresAt: expire,
			Issuer:    "self",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString([]byte(global.TYD_CONFIG.GetString("app.key")))
	return ss, err
}

func ParseToken(tokenString string) (*CustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(global.TYD_CONFIG.GetString("app.key")), nil
	})
	if token != nil {
		if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
			return claims, nil
		}
	}
	return nil, err

}
